﻿using System;
using System.Globalization;
using Windows.Devices.Geolocation;
using BuddyTracker.Interfaces;
using BuddyTracker.Model;

namespace BuddyTracker.ViewModel.Encoders
{
	/// <summary>
	/// Basic location encoder, Geopoint to string and vice-versa.
	/// </summary>
	class TextLocationEncoder : ILocationEncoder
	{
		/// <summary>
		/// Encodes the location into application compatible string.
		/// </summary>
		/// <param name="location">Geopoint for encoding.</param>
		/// <returns>Application compatible string containgng location coordinates in plain text.</returns>
		public string EncodeLocation(Geopoint location)
		{
			return "FLWR|TEXT|" + location.Position.Latitude.ToString("0.00000", CultureInfo.InvariantCulture) + "|" + location.Position.Longitude.ToString("0.00000", CultureInfo.InvariantCulture) + "|" + DateTime.Now.ToString("dd.MM.yyyy|HH:mm:ss", CultureInfo.InvariantCulture);
		}

		/// <summary>
		/// Decodes the application compatible string.
		/// </summary>
		/// <param name="s">String for decoding.</param>
		/// <returns>Geopoint with coordinates from the input string.</returns>
		public User DecodeString(string s)
		{
		  try
		  {
              if (s.StartsWith("FLWR|TEXT"))
			{
				var array = s.Split('|');
				var lat = Double.Parse(array[2], CultureInfo.InvariantCulture);
				var lon = Double.Parse(array[3], CultureInfo.InvariantCulture);
				var g = new Geopoint(new BasicGeoposition() { Latitude = lat, Longitude = lon });
				
				//going to use this pattern for date mm.DD.yyyy and parse it manually!

				var dateString = array[4];
				var timeString = array[5];

				var date = dateString.Split('.');
				var day = int.Parse(date[0]);
				var month = int.Parse(date[1]);
				var year = int.Parse(date[2]);

				var time = timeString.Split(':');
				var hour = int.Parse(time[0]);
				var minute = int.Parse(time[1]);
				var second = int.Parse(time[2]);

				var datetime = new DateTime(year, month, day, hour, minute, second);
				var name = "placeholder";

				return new User() { ScreenName = name, LastLocation = g, LastSeen = datetime };
			}                
			else
				return null;
		  } catch
		  {
			  return null;
		  }
		}

	}
}
